package xjh.him.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xjh.him.R;

public class GlideUtil {
    /**
     * 占位图
     */
    public static final int PLACE_HOLDER_IMAGE_RID = R.drawable.place_holder_image;
    public static final int PLACE_HOLDER_AVATAR_RID = R.drawable.place_holder_avatar;
    /**
     * 错误图
     */
    public static final int ERROR_IMAGE_RID = R.drawable.error_image;
    private static final int ROUND_RADIUS = 10;

    /**
     * 注意 Glide 的操作都不是在 UI 线程下执行的
     * Glide 会创建自己的线程，等拉取到文件资源后，异步设置 view
     */

    public static void preloadImage(Context ctx, String url) {
        Glide.with(ctx).load(url).preload();
    }

    public static void loadImage(Context ctx, String url, ImageView imageView,
                                 RequestOptions opts) {
        Glide.with(ctx).load(url).apply(opts).into(imageView);
    }

    public static RequestOptions defaultImageOpt() {
        return new RequestOptions()
                .placeholder(PLACE_HOLDER_IMAGE_RID)
                .error(ERROR_IMAGE_RID);
    }

    public static RequestOptions defaultRoundedAvatarOpt() {
        return new RequestOptions()
                .placeholder(PLACE_HOLDER_AVATAR_RID)
                .error(ERROR_IMAGE_RID)
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(ROUND_RADIUS)));
    }

    public static void setBitmap(Context ctx, String url, TextView view) {
        Glide.with(ctx).asBitmap().load(url)
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(ROUND_RADIUS)))
                .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                SpannableString text = new SpannableString(" ");
                ImageSpan imageSpan = new ImageSpan(ctx, resource);
                text.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                view.setText(text);
            }
        });
    }
}
